package com.nuoniu.sibanyun.service.crm.call.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.entity.crm.call.CrmCallSettings;
import com.nuoniu.sibanyun.mapper.crm.call.CrmCallSettingsMapper;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallSettingsService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户管理-外呼管理-外呼基础设置 服务实现类
 * </p>
 *
 * @author 白强
 * @since 2022-03-14
 */
@Service
public class CrmCallSettingsServiceImpl extends ServiceImpl<CrmCallSettingsMapper, CrmCallSettings> implements ICrmCallSettingsService {

    @Override
    public List<CrmCallSettings> listCrmCallSettings() {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<CrmCallSettings> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        return list(queryWrapper);
    }

    @Override
    public void batchSaveCrmCallSettings(List<CrmCallSettings> crmCallSettingsList) {
        List<CrmCallSettings> saveList = new ArrayList<>();
        UserInfo userInfo = UserThreadLocal.get();
        Integer companyId = userInfo.getCompanyId();
        QueryWrapper<CrmCallSettings> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("company_id", companyId);
        List<CrmCallSettings> list = list(queryWrapper);
        Set<Long> ids = list.stream().map(CrmCallSettings::getId).collect(Collectors.toSet());
        crmCallSettingsList.forEach(item->{
            Long id = item.getId();
            if(null == id || ids.contains(id)){
                item.setCompanyId(companyId);
                saveList.add(item);
            }
        });
        this.saveOrUpdateBatch(saveList);
    }
}
